package com.smbms.controller;

import com.smbms.entity.User;
import com.smbms.service.UserService;
import com.smbms.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * 用户控制层
 */
@Controller
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 获取所有的用户列表
     * @return
     */
    @RequestMapping("getList")
    @ResponseBody
    public Result getList(User user){
        List<User> userList=this.userService.getList(user);
        return Result.reOk("查询成功",userList);
    }

    /**
     * 获取所有的用户列表
     * @return
     */
    @RequestMapping("login")
    @ResponseBody
    public Result login(String userCode, String userPassword, HttpSession session){
        if(StringUtils.isEmpty(userCode)){
            return Result.reError("用户账户不能为空");
        }
        if(StringUtils.isEmpty(userCode)){
            return Result.reError("用户密码不能为空");
        }
        User user=this.userService.login(userCode,userPassword);
        if(user==null){
            return Result.reError("账号密码错误");
        }
        session.setAttribute("user",user);
        return Result.reOk("登录成功",user);
    }

    /**
     * 查询当前用户
     * @return
     */
    @RequestMapping("getId")
    @ResponseBody
    public Result getId(Integer id){
        User user=this.userService.getId(id);
        return Result.reOk("查询成功",user);
    }

    /**
     * 新增用户
     * @return
     */
    @RequestMapping("save")
    @ResponseBody
    public Result save(User user){
        user.setCreationDate(new Date());
        return this.userService.save(user);
    }

    /**
     * 修改用户
     * @return
     */
    @RequestMapping("update")
    @ResponseBody
    public Result update(User user){
        user.setModifyDate(new Date());
        return this.userService.update(user);
    }


}
